package com.lushuai.jiubeidanci;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.MenuItem;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.lushuai.jiubeidanci.fragment.HomeFragment;
import com.lushuai.jiubeidanci.fragment.ProfileFragment;

public class MainActivity extends AppCompatActivity {
    private BottomNavigationView bottomNavigationView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        bottomNavigationView = findViewById(R.id.bottom_navigation);
        bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                int id = item.getItemId();
                
                if (id == R.id.navigation_home) {
                    loadFragment(new HomeFragment());
                    return true;
                } else if (id == R.id.navigation_profile) {
                    // 检查登录状态
                    if (checkLoginStatus()) {
                        loadFragment(new ProfileFragment());
                    } else {
                        // 未登录则跳转到登录界面
                        startActivity(new Intent(MainActivity.this, LoginActivity.class));
                        // 选中之前的tab
                        bottomNavigationView.setSelectedItemId(bottomNavigationView.getSelectedItemId());
                    }
                    return true;
                }
                return false;
            }
        });

        // 默认选中首页
        bottomNavigationView.setSelectedItemId(R.id.navigation_home);
    }

    private void loadFragment(Fragment fragment) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.fragment_container, fragment);
        transaction.commit();
    }

    // 检查登录状态
    private boolean checkLoginStatus() {
        SharedPreferences sp = getSharedPreferences("user_info", MODE_PRIVATE);
        return sp.getLong("user_id", -1) != -1;
    }

    // 处理从登录界面返回的结果
    @Override
    protected void onResume() {
        super.onResume();
        // 如果当前选中的是个人中心，且已登录，则加载个人中心Fragment
        if (bottomNavigationView.getSelectedItemId() == R.id.navigation_profile && checkLoginStatus()) {
            loadFragment(new ProfileFragment());
        }
    }
}